﻿using Core.DataAccess.Model;
using Core.DataAccess.Model.iTool.Logger;
using Core.Framework;
using Log.Interface;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Log.Implements
{
    public class LogTrackings : ILogTracking
    {
        public async Task<List<LogTracking>> GetTracking(Pagination pagination, string searchValue, DateTime? startdate, DateTime? enddate)
        {
            if (string.IsNullOrWhiteSpace(AppSetting.iToolLoggerSqlString)) return new List<LogTracking>();


            await using (iToolLoggerContext context = new iToolLoggerContext())
            {
                var tokenlist = await context
                            .LogTrackings.ToListAsync();
                if (!string.IsNullOrEmpty(searchValue))
                {
                    tokenlist = tokenlist.Where(a => a.Action.Contains(searchValue)).ToList();
                }
                if (startdate.HasValue)
                {
                    tokenlist = tokenlist.Where(a => a.Createtime >= startdate.Value).ToList();
                }
                if (enddate.HasValue)
                {
                    tokenlist = tokenlist.Where(a => a.Createtime <= enddate.Value).ToList();
                }
                var token = tokenlist.OrderByDescending(a => a.Createtime).GroupBy(a => a.Token).Select(a => a.FirstOrDefault().Id).ToList();

                var result = context
                               .LogTrackings.Where(a => token.Contains(a.Id)).OrderByDescending(a => a.Createtime)
                               .PaginationAsync(pagination);
                return await result;
            }
        }
        public async Task<List<LogTracking>> GetTrack()
        {
            if (string.IsNullOrWhiteSpace(AppSetting.iToolLoggerSqlString)) return new List<LogTracking>();

            await using (iToolLoggerContext context = new iToolLoggerContext())
            {
                return await context
                              .LogTrackings.ToListAsync();
            }
        }
    }
}
